import fetch from 'dva/fetch';
import {getLoginSession} from '../plugin/loginSession';

function parseJSON(response) {
    return response.blob();
}

function checkStatus(response) {
    if(response.status >= 200 && response.status < 300) {
        return response;
    }
    const error = new Error(response.statusText);
    error.response = response;
    throw error;
}

function formatOpt(data) {
    let arr = [];
    if(data) {
    	for(let name in data) {
	    	if(data[name]) {
	    		arr.push(encodeURIComponent(name) + '=' + encodeURIComponent(data[name]));
	    	}
	    };
    }
    // 添加一个随机数，防止缓存
    arr.push('_r=' + Math.floor(Math.random() * 10000 + 500));
    return arr.join('&');
}

export default function download(url, options, filename) {
    options = options || {};
    options.method = options.method || 'post';
    options.mode = options.mode || 'cors';
    options.headers = options.headers || {};
    options.headers['Content-Type'] = options.headers['Content-Type'] || 'application/x-www-form-urlencoded';
    let data = options.data || {};
    let dataBody;
    let loginSession = getLoginSession();
	if(loginSession && loginSession.token) {
		let token = loginSession.token;
		data.channel = token.channel;
		data.token = token.token;
	}
    dataBody = formatOpt(data);
    if(options.body && dataBody) dataBody = options.body + '&' + dataBody;
    options.body = dataBody;
    return fetch(url, options)
    	.then(response => response.blob().then(blob => {
	      	let a = document.createElement('a');
	      	let url = window.URL.createObjectURL(blob);
	      	if(!filename) filename = response.headers.get('Content-Disposition');
	      	a.href = url;
	      	if(filename) a.download = filename;
	      	a.click();
	      	window.URL.revokeObjectURL(url);
	      	a.remove();
	      	options.callback && options.callback();
    	})); 
}